#include "ConfigManager.h"
#include "../utils/cJSON/cJSON.h"
#include <fstream>
#include <sstream>
#include <iostream>

ConfigManager &ConfigManager::getInstance()
{
    static ConfigManager instance;
    return instance;
}

bool ConfigManager::loadConfig(const std::string &filePath)
{
    std::ifstream ifs(filePath);
    if (!ifs.is_open())
        return false;

    std::stringstream buffer;
    buffer << ifs.rdbuf();
    std::string content = buffer.str();

    cJSON *root = cJSON_Parse(content.c_str());
    if (!root)
        return false;

    configData.clear();
    cJSON *item = root->child;
    while (item)
    {
        std::cout << item->string << ": " << item->valuestring << std::endl;
        configData[item->string] = item->valuestring ? item->valuestring : "";
        item = item->next;
    }

    cJSON_Delete(root);
    return true;
}

bool ConfigManager::saveConfig(const std::string &filePath) const
{
    cJSON *root = cJSON_CreateObject();
    for (const auto &[key, value] : configData)
    {
        cJSON_AddStringToObject(root, key.c_str(), value.c_str());
    }

    char *jsonStr = cJSON_Print(root);
    std::ofstream ofs(filePath);
    if (!ofs.is_open())
    {
        cJSON_free(jsonStr);
        cJSON_Delete(root);
        return false;
    }

    ofs << jsonStr;
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    return true;
}

std::string ConfigManager::get(const std::string &key) const
{
    auto it = configData.find(key);
    return it != configData.end() ? it->second : "";
}

void ConfigManager::set(const std::string &key, const std::string &value)
{
    configData[key] = value;
}
